#!/usr/bin/python
import os
import sys
import MySQLdb
import string
import time

def getResourceLeft(): 
   return 0


def isDigtal(myNum):
    nums = string.digits
    if type(myNum) is not str:
        return False
    else:
        for temp in myNum:
            if temp not in nums:
                return False
        return True
        
def checkParameter(conn):
    global job_id

    if not conn:
        print "Can not connect to database, Fail!"
        return -1
    paraCnt=len(sys.argv)
    if paraCnt != 2:
        return 0
    job_id=str(sys.argv[1])
    if not isDigtal(job_id):
        return 0

    flag = conn.execute("select job_id from jobs where job_id = " + job_id);
    if flag == 0:
        print "No Job ", job_id
        return 0
    return 1
    

def delJobs(conn,job_id):
     
    tmp = str(time.time()).split('.')
    thistime=tmp[0]

    conn.execute("update jobs set status = 'finish' where job_id="+job_id)
    conn.execute("update jobs set end_time = " + thistime + " where job_id = " + job_id)
    
    conn.execute("select vm_ip from job_resource where job_id="+job_id)
    rows=conn.fetchall()
    for tmp in rows:
        conn.execute("update macaddress set used='n' where ip = '"+str(tmp[0])+"'") 
      
    conn.execute("select ip, img_path,hvm_path,vm_uuid from vm_store where job_id="+job_id)
    rows = conn.fetchall()
    for tmp in rows:
        os.popen("ssh root@"+tmp[0]+ " xm shutdown "+str(tmp[3]))
        os.popen("ssh root@"+tmp[0]+ " rm -f "+str(tmp[1]))
        os.popen("ssh root@"+tmp[0]+ " rm -f "+str(tmp[2]))
    print "Job "+job_id+" is deleted!"
job_id="0"
tr_command="command format:\n" + \
"   cjob job_id\n" + \
"   For example: cjob 1"

if __name__ == "__main__":
    connect=MySQLdb.connect(host="localhost",port=3306,user="root",passwd="passw0rd",db="cloud")
    conn=connect.cursor()
    print connect,conn
    flag = checkParameter(conn)
    if flag == -1:
        sys.exit(0)
    if flag == 0:
        print str_command
        sys.exit(0)
    delJobs(conn,job_id) 
    conn.close()
    connect.close()

